package com.swd.order.controller;


import com.github.pagehelper.Page;
import com.swd.order.model.Category;
import com.swd.order.model.FoodSaveModel;
import com.swd.order.model.Foods;
import com.swd.order.model.FoodsSlave;
import com.swd.order.service.CategoryService;
import com.swd.order.service.FoodsService;
import com.swd.order.util.ImgUtil;
import com.swd.order.util.PageVo;
import com.swd.order.vo.Ret;
import com.swd.order.vo.Rets;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.util.Base64Utils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import sun.net.util.URLUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.net.URL;
import java.security.PublicKey;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("foods")
@Slf4j
public class FoodsContoller {

    @Autowired
    private FoodsService foodsService;
    @Value("${upload}")
    private String uploadPath;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DataSourceTransactionManager dataSourceTransactionManager;
    @Autowired
    private TransactionDefinition transactionDefinition;

    @PostMapping("save")
    public Ret save(@RequestBody FoodSaveModel foods) {


        List<Foods> foodsList = foodsService.queryByName(foods.getName());

        if (foodsList.size() > 0) {
            log.error("保存失败,已存在同名菜品");
            return Rets.failure("已有" + foods.getName());
        }


        if (!foods.getIsSetMeal()) {

            Category category = categoryService.queryById(foods.getCategoryId());

            if (category == null) {
                log.error("保存失败,改分类不存在");
                return Rets.success("该分类不存在，请另选择");
            }
        }

        String base64 = StringUtils.delete(foods.getImageUrl(), "data:image/jpeg;base64,");

        byte[] bytes = Base64Utils.decodeFromString(base64);
        String fileName = UUID.randomUUID() + ".jpg";

        try {
            File file = new File(uploadPath + fileName);
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            fileOutputStream.write(bytes);
            fileOutputStream.close();
            ImgUtil.compression(bytes, 200, 200, uploadPath + "ys-" + fileName);
        } catch (Exception e) {
            log.error("图片保存失败", e);
            return Rets.failure("图片保存失败");
        }

        TransactionStatus transactionStatus = dataSourceTransactionManager.getTransaction(transactionDefinition);

        Foods food = new Foods();
        food.setName(foods.getName());
        food.setPicture(fileName);
        food.setCount(0);
        food.setDescription(foods.getDescription());
        food.setSetMeal(foods.getIsSetMeal());
        food.setOftenMeal(true);
        food.setEnable(true);
        food.setTags(foods.getTags());
        boolean save;
        if (foods.getIsSetMeal()) {

            if (foods.getIdList() == null || foods.getIdList().size() == 0) {
                dataSourceTransactionManager.rollback(transactionStatus);
                return Rets.failure("必须勾选普通菜品！");
            }

            List<Category> categories = categoryService.queryByName("套餐");
            food.setCategoryId(categories.get(0).getId());
            save = foodsService.saveSetMeal(food, foods.getIdList());
        } else {
            food.setCategoryId(foods.getCategoryId());
            save = foodsService.save(food);
        }

        if (save) {
            dataSourceTransactionManager.commit(transactionStatus);
            return Rets.success("保存失败");
        } else {
            dataSourceTransactionManager.rollback(transactionStatus);
            return Rets.failure("保存失败");
        }
    }

    @RequestMapping("update")
    public Ret update(@RequestBody FoodSaveModel foods) {


        log.info("更新菜品数据{}", foods);

        if (foods.getId() == null) {

            return Rets.failure("该菜品不存在");
        }

        Foods foodsOld = foodsService.queryById(foods.getId());
        Foods foodNew = new Foods();


        if (!foods.getImageUrl().startsWith("http") && foods.getImageUrl().startsWith("data:image/jpeg;base64,")) {
            log.info("修改图片");
            String base64 = StringUtils.delete(foods.getImageUrl(), "data:image/jpeg;base64,");
            byte[] bytes = Base64Utils.decodeFromString(base64);
            String fileName = UUID.randomUUID() + ".jpg";
            try {
                File file = new File(uploadPath + fileName);
                FileOutputStream fileOutputStream = new FileOutputStream(file);
                fileOutputStream.write(bytes);
                fileOutputStream.close();
                foodNew.setPicture(fileName);
                ImgUtil.compression(bytes, 200, 200, uploadPath + "ys-" + fileName);
            } catch (Exception e) {
                log.error("图片保存失败", e);
                return Rets.failure("图片保存失败");
            }
        }
        TransactionStatus transactionStatus = dataSourceTransactionManager.getTransaction(transactionDefinition);

        foodNew.setId(foodsOld.getId());
        foodNew.setCategoryId(foods.getCategoryId());
        foodNew.setName(foods.getName());
        foodNew.setDescription(foods.getDescription());
        foodNew.setTags(foods.getTags());

        boolean success = foodsService.update(foodNew);

        if (foodsOld.getSetMeal()) {
            boolean itemSuccess = foodsService.updateItem(foods.getId(), foods.getIdList());
            if (!itemSuccess) {
                return Rets.failure("修改失败");
            }
        }

        if (success || foodNew.equals(foodsOld)) {
            dataSourceTransactionManager.commit(transactionStatus);
            return Rets.success("修改成功");
        }
        dataSourceTransactionManager.rollback(transactionStatus);
        return Rets.failure("修改失败");
    }

    @RequestMapping("updateState")
    public Ret updateState(@RequestBody Foods foods) {

        if (foods.getId() == null) {
            return Rets.failure("id不能为空");
        }

        boolean update = foodsService.update(foods);

        if (update) {
            return Rets.success("更改成功");
        }
        return Rets.failure("更改失败");
    }

    @GetMapping("all")
    public Ret queryAll() {
        List<Foods> foodsList = foodsService.queryAll();
        return Rets.success(foodsList);
    }

    @PostMapping("query")
    public Ret query(@RequestParam(required = false) Integer categoryId,
                     @RequestParam(required = false, defaultValue = "") String name,
                     @RequestParam(required = false, defaultValue = "1") int pageNum,
                     @RequestParam(required = false, defaultValue = "5") int limit) {

        Page<Foods> query = foodsService.query(categoryId, name, pageNum, limit);

        return Rets.success(PageVo.build(query));
    }

    @PostMapping("delete")
    public Ret delete(int id) {

        boolean success = foodsService.delete(id);

        if (!success) {
            return Rets.failure("删除失败");
        }
        return Rets.success("删除成功");
    }

    @PostMapping("sort")
    public Ret sort(@RequestBody List<Integer> idSortList) {

        foodsService.sort(idSortList);
        return Rets.success();
    }

    @GetMapping("clearImage")
    public Ret clearImage() {
        File absoluteFile = new File(uploadPath).getAbsoluteFile();
        List<Foods> foodsList = foodsService.queryAll();
        Map<String, String> collect = foodsList.stream().collect(Collectors.toMap(Foods::getPicture, Foods::getPicture));
        String[] list = absoluteFile.list((dir, name) -> !name.startsWith("ys-") && !name.startsWith("banner"));
        if (list == null) {
            return Rets.failure("无多余图片");
        }
        int i = 0;
        List<String> fail = new ArrayList<>();
        for (String s : list) {
            if (StringUtils.isEmpty(collect.get(s))) {
                boolean delete = new File(uploadPath + s).delete();
                boolean delete1 = new File(uploadPath + "ys-" + s).delete();
                if (delete && delete1) {
                    i++;
                } else {
                    fail.add(s);
                    fail.add("ys-" + s);
                }
            }
        }
        return Rets.success("已清理" + i + "张图片,失败:" + fail);
    }

    @GetMapping("compression")
    public Ret compression() throws IOException {
        List<Foods> foodsList = foodsService.queryAll();
        List<String> collect = foodsList.stream().map(Foods::getPicture).collect(Collectors.toList());

        for (String item : collect) {
            if (!item.startsWith("ys-") || !item.startsWith("bann")) {
                ImgUtil.compression(uploadPath + item, 1080, 1080, uploadPath + item);
            }
        }
//        collect.stream().parallel()
        return Rets.success();
    }
}
